<?php

namespace App\Repositories\Eloquent\Mgt;

use Illuminate\Container\Container as App;
use App\Repositories\Eloquent\Repository;
use Session;

use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;

use AlibabaCloud\Client\AlibabaCloud as AliCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class UtilRepository extends Repository
{
    public function __construct(App $app)
    {
        parent::__construct($app);

    }

    function model()
    {
        return 'App\Models\Mgt\Util';
    }


    /**
     * [验证码]
     * @return [type] [description]
     */
    public function captcha()
    {
        $phraseBuilder = new PhraseBuilder(4, '0123456789');

        $captcha = new CaptchaBuilder(null, $phraseBuilder);
        $captcha->setBackgroundColor(247,247,247);
        $captcha->setMaxBehindLines(0);
        $captcha->setMaxFrontLines(0);
        $captcha->build(110,35);

        $phrase = $captcha->getphrase();

        Session::put('captcha', $phrase);
        header('Cache-Control: no-cache, must-revalidate');
        header('Content-type: image/jpeg');

        return $captcha->output();
    }


    /**
     * [二次验证安全码]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function safecode($request)
    {
        $safecode = $request->safecode;

        if( $safecode != SAFECODE)
            return $this->responseFail('安全码错误');

        return $this->responseSuccess('安全码正确', $safecode);
    }

    /**
     * 生成验证码
     * @return [type] [description]
     */
    public function smscode($new = null)
    {
        if($new){

            $send = rand(100000,999999);

            Session::put('smscode', $send);
        }
        else{
            if( !Session::get('smscode') ){

                $send = rand(100000,999999);

                Session::put('smscode', $send);

            }else{

                $send = Session::get('smscode');
            }
        }

        return (string)$send;
    }


    public function sendSms($request,$config = 'sms')
    {
        $mobile = $request->mobile;

        if (empty($mobile) || strlen($mobile)!== 11) {
            return $this->responseFail(405, '手机格式不正确');
        }

        $option = array('PhoneNumbers' => $mobile,
                      'SignName'=>config($config.'.sign'),
                      'TemplateCode' => config($config.'.option.login.code'),
                      'TemplateParam' => json_encode( array('code'=>$this->smscode(true)) ) );

        $result = $this->send($option,$config)->toArray();

        if( isset($result['Code']) && strcmp($result['Code'], 'OK') === 0)
            return $this->responseSuccess('验证码已发送', $result);

        return $this->responseFail(500, '验证码发送失败');

    }


    /**
     * 短信发送
     * @param  array  $option [description]
     * @return [type]         [description]
     */
    protected function send(array $option, $config)
    {
        $query = array( 'RegionId' => config($config.'.regionId') );

        if(isset($option)){
            $query = collect($query)->merge(collect($option));
        }
        $opt = array('query'=>$query->toArray());

        AliCloud::accessKeyClient( config($config.'.accessKey'), config($config.'.accessSecret') )
            ->regionId(config($config.'.regionId'))
            ->asDefaultClient();

        try {
            $result = AliCloud::rpc()
                ->product(config($config.'.product'))
                ->version(config($config.'.version'))
                ->action(config($config.'.action'))
                ->method(config($config.'.method'))
                ->host(config($config.'.host'))
                ->options($opt)
                ->request();

            return $result;

        } catch (ClientException $e) {
            return $this->responseFail(500, '短信发送失败Client');

        } catch (ServerException $e) {
            return $this->responseFail(500, '短信发送失败Server');
        }
    }


    public function schools($request)
    {
        $term = $request->term;
        $schools = \App\Models\Mgt\School::where('name','like',"%$term%")->get();
        return $schools->toJson();
    }

    public function users($request)
    {
        $query = $request->term;

        //匹配到全数字，按账号查找

        if (preg_match('/^\d+$/i', $query)) {

            if( strlen($query) < 5)  return null;

            if(strlen($query) == 5){
                $result = \App\Models\Mgt\User::where('account', $query)
                    ->orderBy('id','desc')
                    ->get();
            }
            else{
                $result = \App\Models\Mgt\User::where('mobile','like',"%$query%")
                    ->orderBy('id','desc')
                    ->get();
            }

        }
        //未匹配到数字，按姓名查找
        else {
            $result = \App\Models\Mgt\User::where('name','like',"%$query%")
                ->orderBy('id','desc')
                ->get();
        }

        return $result->toJson();
    }
}